package model

import (
	"log"
	"raymond/global"
	"time"
)

const table_bsn_main_wallets = "t_bsn_main_wallets"

type BSNMainWallet struct {
	Id         int64     `db:"id"`
	Priv       string    `db:"priv"`
	BNBAddr    string    `db:"bnb_addr"`
	TRONAddr   string    `db:"tron_addr"`
	Mnemonics  string    `db:"mnemonics"`
	Remark     string    `db:"remark"`
	CreateTime time.Time `db:"ct"`
	UpdateTime time.Time `db:"ut"`
}

func (cw *BSNMainWallet) CreateBSNMainWallet() error {
	now := time.Now().UTC()
	model := &BSNMainWallet{
		Priv:       cw.Priv,
		BNBAddr:    cw.BNBAddr,
		TRONAddr:   cw.TRONAddr,
		Mnemonics:  cw.Mnemonics,
		CreateTime: now,
		UpdateTime: now,
	}
	result, err := global.DB().NamedExec("insert into "+table_bsn_main_wallets+" (priv, bnb_addr, tron_addr, mnemonics, create_time, update_time)"+
		" values (:priv,:bnb_addr,:tron_addr,:mnemonics,:ct,:ut)",
		&model)
	if err != nil {
		return err
	}
	cw.Id, _ = result.LastInsertId()
	return nil
}

func AllBSNMainWallet() *[]BSNMainWallet {
	var wallets []BSNMainWallet
	err := global.DB().Select(&wallets, "select bnb_addr, tron_addr from "+table_bsn_main_wallets)
	if err != nil {
		log.Println(err)
		return nil
	}
	return &wallets
}

func GetBSNWalletByAddr(chain global.CHAIN, address string) (*BSNMainWallet, error) {
	var wallets []BSNMainWallet
	var addrFieldName string
	if string(chain) == string(global.BNB) {
		addrFieldName = "bnb_addr"
	} else {
		addrFieldName = "tron_addr"
	}
	sql := "select id, priv, bnb_addr, tron_addr, mnemonics from " + table_bsn_main_wallets + " where " + addrFieldName + " = ? order by update_time desc limit 1"
	err := global.DB().Select(&wallets, sql, address)
	if err != nil {
		return nil, err
	}
	return &wallets[0], nil
}
